package cn.com.libertymutual.core.security.encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Hex;

import cn.com.libertymutual.core.util.HexBinary;
import cn.com.libertymutual.core.util.uuid.UUID;

import com.google.common.base.Strings;

/**
 * MD5密码加密
 * 
 * @author bob
 * 
 */
public class Md5PwdEncoder implements PwdEncoder {
	///private static MessageDigest MD5 = null; 
	
	public String encodePassword(String rawPass) {
		return encodePassword(rawPass, defaultSalt);
	}

	public String encodePassword(String rawPass, String salt) {
		String saltedPass = mergePasswordAndSalt(rawPass, salt, false);
		MessageDigest messageDigest = getMessageDigest();
		byte[] digest;
		try {
			digest = messageDigest.digest(saltedPass.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			throw new IllegalStateException("UTF-8 not supported!");
		}
		return new String(Hex.encodeHex(digest));
	}

	public boolean isPasswordValid(String encPass, String rawPass) {
		return isPasswordValid(encPass, rawPass, defaultSalt);
	}

	public boolean isPasswordValid(String encPass, String rawPass, String salt) {
		if (encPass == null) {
			return false;
		}
		String pass2 = encodePassword(rawPass, salt);
		return encPass.equals(pass2);
	}

	protected final MessageDigest getMessageDigest() {
		////if( MD5 != null ) return MD5;
		
		MessageDigest MD5 = null;
		String algorithm = "MD5";
		try {
			MD5 = MessageDigest.getInstance(algorithm);
		} catch (NoSuchAlgorithmException e) {
			throw new IllegalArgumentException("No such algorithm ["
					+ algorithm + "]");
		}
		
		return MD5;
	}

	/**
	 * Used by subclasses to extract the password and salt from a merged
	 * <code>String</code> created using
	 * {@link #mergePasswordAndSalt(String,Object,boolean)}.
	 * <p>
	 * The first element in the returned array is the password. The second
	 * element is the salt. The salt array element will always be present, even
	 * if no salt was found in the <code>mergedPasswordSalt</code> argument.
	 * </p>
	 * 
	 * @param mergedPasswordSalt
	 *            as generated by <code>mergePasswordAndSalt</code>
	 * 
	 * @return an array, in which the first element is the password and the
	 *         second the salt
	 * 
	 * @throws IllegalArgumentException
	 *             if mergedPasswordSalt is null or empty.
	 */
	protected String mergePasswordAndSalt(String password, Object salt,
			boolean strict) {
		if (password == null) {
			password = "";
		}
		if (strict && (salt != null)) {
			if ((salt.toString().lastIndexOf("{") != -1)
					|| (salt.toString().lastIndexOf("}") != -1)) {
				throw new IllegalArgumentException(
						"Cannot use { or } in salt.toString()");
			}
		}
		
		if ((salt == null) || "".equals(salt)) {
			return password;
		} else {
			return String.format("%s{%s}", password , salt.toString() );
		}
	}
	
	/** 
     * 对一个字符串获取md5值 
     * @return md5串 
     */ 
	public String getSHAMD5Code( String str ) {
		
		if( Strings.isNullOrEmpty(str) ) {
			return UUID.getShortUuid();
		}
		
		byte[] strbytes = str.getBytes();
		
		getMessageDigest().update( strbytes, 0, strbytes.length );

		return new String(HexBinary.encode( getMessageDigest().digest() ));

    }
	
	/**
	 * 混淆码。防止破解。
	 */
	private String defaultSalt;

	/**
	 * 获得混淆码
	 * 
	 * @return
	 */
	public String getDefaultSalt() {
		return defaultSalt;
	}

	/**
	 * 设置混淆码
	 * 
	 * @param salt
	 */
	public void setSefaultSalt(String defaultSalt) {
		this.defaultSalt = defaultSalt;
	}
	
	
	
	public static String encodePassword(String password,int maxlength){
	    int s1=97;
	    int s2=76;
	    int len=password==null?0:password.length();

	    if(len>maxlength) len=maxlength;
	    StringBuffer pw=new StringBuffer(2*maxlength);
	    for(int i=0;i<maxlength;i++){
	      int ch,ch1,ch2;
	      ch=i>=len?0:password.charAt(i);
	      ch=(s1+++ch)^s2++;
	      ch1=ch/26+(int)'I';ch2=ch%26+(int)'A';
	      if((i & 1)==1) s2+=ch1&0xf;
	      else s2-=ch1&0xf;
	      pw.append((char)ch1);
	      pw.append((char)ch2);
	    }
	    return new String(pw);
	  }

}
